package com.sfl.api_backend.controller.files;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sfl.api_backend.constant.HttpCode;
import com.sfl.api_backend.entity.Datasets;
import com.sfl.api_backend.entity.Imgs;
import com.sfl.api_backend.entity.Labels;
import com.sfl.api_backend.mapper.DatasetsMapper;
import com.sfl.api_backend.service.IImgsService;
import com.sfl.api_backend.service.ILabelsService;
//import com.sfl.api_backend.service.impl.MqSendService;
import com.sfl.api_backend.utils.Api.RestResult;
import com.sfl.api_backend.utils.RandomID;
import com.sfl.api_backend.vo.imgNewName;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 影像表 前端控制器
 * </p>
 *
 * @author szc
 * @since 2023-01-27
 */
@RestController
@RequestMapping("/files/imgs/img")
@Slf4j
public class ImgsController {

    @Resource
    private IImgsService imgsService;

    @Resource
    private ILabelsService labelsService;

    @Resource
    private DatasetsMapper datasetsMapper;

    @Value("${file.upload.path}")
    private String uploadPath;

//    @Resource
//    private MqSendService mqSendService;



    @PostMapping("/delect")
    @PreAuthorize("hasAuthority('User')")
    public RestResult delect(@RequestBody List<Integer> imgIds) throws  Exception{

        log.info("delect imgs: {}", imgIds);
        // 由于影像集和标签集是一对多的关系，所以在删除影像的时候，需要先删除标签集

        Wrapper<Labels> wrapper = new LambdaQueryWrapper<>();
        ((LambdaQueryWrapper<Labels>) wrapper).eq(Labels::getImgId, imgIds);

        List<Labels> labels = labelsService.list(wrapper);
        for (Labels label : labels) {
            File file = new File(label.getLabelPath());
            if (file.exists()) {
                file.delete();
            }
        }

        List<Imgs> imgs = imgsService.listByIds(imgIds);
        for (Imgs img : imgs) {
            File file = new File(img.getImgPath());
            if (file.exists()) {
                file.delete();
            }
        }

        labelsService.remove(wrapper);
        imgsService.removeBatchByIds(imgIds);
        return RestResult.success();
    }

    @PostMapping("/make")
    @PreAuthorize("hasAuthority('User')")
    public RestResult make(@RequestParam("files[]") List<MultipartFile> files,@RequestParam("names[]") List<String> names,@RequestParam("Ids[]") List<String> Ids) throws Exception{

        String imgsetPath = uploadPath + Ids.get(1) + "/datasets/" + Ids.get(0) + "/org_img/";
        String view_path = uploadPath + Ids.get(1) + "/datasets/" + Ids.get(0) + "/view_img/";
        for (int i=0; i < files.size(); i++){
            MultipartFile file = files.get(i);
            String name = names.get(i);
            if(!file.isEmpty()){
                name = name.substring(name.indexOf("/"));
                File fileToSave = new File(imgsetPath, name);
                try(OutputStream outputStream = new FileOutputStream(fileToSave)){
                    outputStream.write(file.getBytes());
                    Imgs imgs = new Imgs();
                    imgs.setImgId(RandomID.getRandomID());
                    imgs.setImgName(name);
                    imgs.setImgsetId(Integer.valueOf(Ids.get(0)));
                    imgs.setImgPath(imgsetPath + name);
                    imgs.setUserId(Integer.valueOf(Ids.get(1)));
                    imgs.setCreateTime(LocalDateTime.now());
                    imgs.setViewPath(view_path + name);
                    imgsService.save(imgs);
                }
                catch (Exception e){
                    return RestResult.error(500, String.valueOf(e));
                }
            }

        }


        Map<String, String> mqMap = new HashMap<>();
        mqMap.put("org_img", imgsetPath);
        mqMap.put("view_img", view_path);

//        mqSendService.sendConvertTask(JSON.toJSONString(mqMap));

        return RestResult.success();
    }

    @PostMapping("/modify")
    @PreAuthorize("hasAuthority('User')")
    public RestResult modifly(@RequestBody imgNewName vo)
    {
        try {
            log.info("modify imgs: {}", vo);
            Imgs imgs = imgsService.getById(vo.getImgId());
            imgs.setImgName(vo.getNewName());
            imgsService.updateById(imgs);
            return RestResult.success();
        }
        catch (Exception e) {
            log.error("modify imgs: {} error", vo);
            return RestResult.error(HttpCode.NOT_IMPLEMENTED, e.getMessage());
        }
    }

    @PostMapping("/list")
    @PreAuthorize("hasAuthority('User')")
    public RestResult list(@RequestBody Datasets datasets)
    {
        try {
            log.info("list imgs: {}", datasets.getImgsetId());
            Wrapper<Imgs> wrapper = new LambdaQueryWrapper<>();
            ((LambdaQueryWrapper<Imgs>) wrapper).eq(Imgs::getImgsetId, datasets.getImgsetId());
            List<Imgs> imgs = imgsService.list(wrapper);

            Datasets datasets1 = datasetsMapper.selectById(datasets.getImgsetId());

            Map<String, Object> map = new HashMap<>();
            map.put("datasets",datasets1);
            map.put("imgs", imgs);
            return RestResult.success(map);
        }
        catch (Exception e) {
            log.error("list imgs: {} error", datasets.getImgsetId());
            return RestResult.error(HttpCode.NOT_IMPLEMENTED, e.getMessage());
        }
    }



}
